//
//  KDFormDataRequest.m
//  KDTools
//
//  Created by 斌 on 15/11/19.
//  Copyright © 2015年 斌. All rights reserved.
//

#import "KDFormDataRequest.h"

#define kTimeoutInterval 60.0f //默认60秒

#define kBoundary @"--KDHttpRequest"
#define kEndBoundary @"--KDHttpRequest--"

@implementation KDFormDataRequest{
    
    NSMutableURLRequest *urlRequest;
    NSMutableData *myRequestData;
    
    NSMutableData *responseData;
    NSURLConnection *conn;
    
}

- (id)initWithURLString:(NSString *)urlString{
    
    urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]
                                         cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                     timeoutInterval:kTimeoutInterval];
    
    myRequestData = [[NSMutableData alloc] init];
    
    return self;
}


- (void)addPostValue:(NSString *)value forKey:(NSString *)key{
    
    NSMutableString *body=[[NSMutableString alloc]init];
    [body appendFormat:@"%@\r\n",kBoundary];
    [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
    [body appendFormat:@"%@\r\n",value];
    
    [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
    
}

- (void)addImageFile:(NSString *)filePath withFileName:(NSString *)name forKey:(NSString *)key{
    
    NSMutableString *body=[[NSMutableString alloc]init];
    [body appendFormat:@"%@\r\n",kBoundary];
    [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n",key,name];
    [body appendFormat:@"Content-Type: image/png\r\n\r\n"];
    
    [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
    
    NSData *imageData = [NSData dataWithContentsOfFile:filePath];
    [myRequestData appendData:imageData];
    
    [myRequestData appendData:[ @"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
}

- (void)addImageData:(NSData *)data withFileName:(NSString *)name forKey:(NSString *)key{
    
    NSMutableString *body=[[NSMutableString alloc]init];
    [body appendFormat:@"%@\r\n",kBoundary];
    [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n",key,name];
    [body appendFormat:@"Content-Type: image/png\r\n\r\n"];
    
    [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
    
    [myRequestData appendData:data];
    
    [myRequestData appendData:[ @"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    
}

- (void)startAsynchronous{
    
    NSString *end = [[NSString alloc]initWithFormat:@"%@",kEndBoundary];
    [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
    
    NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=KDHttpRequest"];
    [urlRequest setValue:content forHTTPHeaderField:@"Content-Type"];
    [urlRequest setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[myRequestData length]] forHTTPHeaderField:@"Content-Length"];
    [urlRequest setHTTPBody:myRequestData];
    [urlRequest setHTTPMethod:@"POST"];
    
    
    conn = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
    if (!conn){
        printf("\nFail ! Error = 用户连接失败。");
    }
    
}


- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite{
    
    _uploadProgressDelegate.progress = bytesWritten/totalBytesWritten;
    
}


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    
    responseData = [NSMutableData data];
    
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    
    [responseData appendData:data];
    
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    
    [_delegate requestFinished:self];
    
}

- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error{
    
    printf("\nFail ! Error = %s",[[error.userInfo objectForKey:@"NSLocalizedDescription"] UTF8String]);
    _error = error;
    
    [_delegate requestFailed:self];
    
}

- (NSString *)responseString{
    
    return [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
}

- (NSData *)responseData{
    
    return responseData;
}


- (void)cancel{
    
    [conn cancel];
}



@end

